package app.keter.portal.exp;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.keter.framework.web.annotation.Sid;
import app.keter.portal.base.BaseController;
import com.keter.framework.web.result.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Feign功能测试
 */
@RestController
@RequestMapping("/public/exp")
public class ExpFeignController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(ExpFeignController.class);
	@Autowired
	ExpFeignClient client;

	@GetMapping("/sid/feign")
	public String sid(@Sid Long sid) {
		//主动生成SID
//		generateSid();
		logger.info("method tid:{}",Thread.currentThread().getId());
		logger.info("sid-threadlocal:{}",sid);
		// feign每次都在一个新的线程里发起请求，不能通过ThreadLocal方式生成唯一ID
		String sid1 = client.sid(sid).string();
		String sid2 = client.sid(sid).string();
		logger.info("sid1:{},sid2:{}",sid1,sid2);
		Assert.isTrue(sid1.equals(sid2),"连续请求时获取的SID不一致！");
		return sid2;
	}

	/**
	 * 聚合服务演示
	 * @return
	 */
	@GetMapping("/aggr/feign")
	public void aggrObject() {
		JSONObject org = client.dataObject().data();
		logger.info("org:{}",org);

		JSONArray users = client.dataArray().data();
		logger.info("users:{}",users);

		String str =client.dataString().data();
		logger.info("str:{}",str);
	}

	/**
	 * Hystrix生效但不包含fallback异常处理方法时：
	 * 会被全局异常拦截器捕获并返回“ExpClient#timeout() failed and fallback failed.”消息
	 * @return
	 */
	@GetMapping("/timeout/feign")
	public JSONResult timeout() {
		return client.timeout();
	}
}
